package com.example.tys.baseapplication.net_tcp.frame.NettyImpl.udp;


import com.example.tys.baseapplication.net_tcp.frame.future.FutureManager;
import com.example.tys.baseapplication.net_tcp.frame.packet.UdpPacket;

import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.TimeoutException;

/**
 * udp
 * 发送消息后阻塞等待，接收消息唤醒等待
 * Created by tys on 2019/4/29.
 */

abstract class UdpReciprocalFuture<PacketRequest extends UdpPacket, PacketResponse extends UdpPacket> extends
        AbstractUdp<PacketRequest, PacketResponse> {
    private FutureManager<PacketResponse> mFutureManager = new FutureManager<>();
    private static final int DEFAULT_WAIT_TIME = 8000;


    /**
     * 发送后。阻塞、等待结果
     *
     * @param packet
     * @param timeOutMillis
     * @return 响应
     * @throws TimeoutException
     * @throws InterruptedException
     * @throws RejectedExecutionException
     */
    @Override
    protected PacketResponse afterSendAndWait(PacketRequest packet, int timeOutMillis) throws TimeoutException, InterruptedException {
        //不支持死等的情况
        return mFutureManager.get(packet.getUniqueId(), timeOutMillis <= 0 ? DEFAULT_WAIT_TIME : timeOutMillis);
    }


    /**
     * 接收到其他主机消息后。设置结果，唤醒阻塞线程
     *
     * @param packet
     */
    @Override
    protected void afterReceive (PacketResponse packet) {
        if (null != packet) {
            mFutureManager.signal(packet);
        }
    }


}

